package com.demo.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class GatewayConfiguration {
    @Autowired
    private KeyResolver hostNameResolver;

    @Autowired()
    @Qualifier("userRateLimiter")
    private RateLimiter reteLimiterUser;

    @Bean
    public RouteLocator routes(RouteLocatorBuilder builder) {
        return builder.routes().route(
                        route -> route.path("/service1/**").filters(f -> {
                            f.requestRateLimiter(c -> {
                                c.setKeyResolver(hostNameResolver);
                                c.setRateLimiter(reteLimiterUser);
                            });
                            f.stripPrefix(1);
                            return f;
                        }).uri("lb://service1"))
                .route(route -> route.path("/service2/**").uri("lb://service2"))
                .build();
    }
}
